<template>
  <u-popup
    :show="visible"
    mode="bottom"
    height="70%"
    @close="handleClose"
  >
    <view class="spec-modal">
      <!-- 规格选项 -->
      <view v-for="(options, specName) in specOptions" :key="specName" class="spec-group">
        <view class="spec-title">{{ specName }}</view>
        <view class="spec-options">
          <u-tag
            v-for="option in options"
            :key="option"
            :text="option"
            :type="getOptionType(specName, option)"
            :disabled="isOptionDisabled(specName, option)"
            @click="selectOption(specName, option)"
          />
        </view>
      </view>

      <!-- SKU 信息 -->
      <view class="sku-info">
        <text>价格：{{ (selectedSku && selectedSku.price) || '-' }} 元</text>
        <text>库存：{{ (selectedSku && selectedSku.stock) || '-' }}</text>
      </view>

      <!-- 数量选择 -->
      <view v-if="selectedSku" class="quantity-box">
        <text>数量：</text>
        <u-number-box
          v-model="quantity"
          :min="1"
          :max="selectedSku.stock || 1"
        />
      </view>

      <!-- 确定按钮 -->
      <u-button
        type="primary"
        :disabled="!selectedSku || selectedSku.stock <= 0"
        @click="confirmSelection"
      >
        确定
      </u-button>
    </view>
  </u-popup>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    skuList: { type: Array, default: () => [] }
  },
  emits: ['update:visible', 'selectSku', 'close'],
  data() {
    return {
      selectedSpecs: {},
      selectedSku: null,
      quantity: 1
    }
  },
  computed: {
    specOptions() {
      const optionsMap = {}
      this.skuList.forEach(sku => {
        for (const [key, value] of Object.entries(sku.specObj || {})) {
          if (!optionsMap[key]) optionsMap[key] = []
          if (!optionsMap[key].includes(value)) optionsMap[key].push(value)
        }
      })
      return optionsMap
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.selectedSpecs = {}
        this.selectedSku = null
        this.quantity = 1
      }
    }
  },
  methods: {
    isSelected(specName, option) {
      return this.selectedSpecs[specName] === option
    },
    isOptionDisabled(specName, option) {
      const tempSelection = { ...this.selectedSpecs, [specName]: option }
      return !this.skuList.some(sku =>
        Object.entries(tempSelection).every(([k, v]) => !v || sku.specObj[k] === v) &&
        sku.stock > 0
      )
    },
    getOptionType(specName, option) {
      if (this.isSelected(specName, option)) {
        return 'primary'
      }
      return this.isOptionDisabled(specName, option) ? 'default' : 'info'
    },
    selectOption(specName, option) {
      if (this.isOptionDisabled(specName, option)) return
      if (this.selectedSpecs[specName] === option) {
        this.$delete(this.selectedSpecs, specName)
      } else {
        this.$set(this.selectedSpecs, specName, option)
      }
      const allSelected = Object.keys(this.specOptions).every(k => this.selectedSpecs[k])
      if (allSelected) {
        const matchSku = this.skuList.find(sku =>
          Object.entries(this.selectedSpecs).every(([k, v]) => sku.specObj[k] === v)
        )
        this.selectedSku = matchSku || null
        if (this.selectedSku) {
          this.quantity = 1 // 重置数量
        }
      } else {
        this.selectedSku = null
        this.quantity = 1
      }
    },
    confirmSelection() {
      if (this.selectedSku) {
		   let safeQuantity = Math.max(1, Math.min(this.quantity, this.selectedSku.stock || 1))
       // this.$emit("selectSku", { ...this.selectedSku, quantity: this.quantity })
       this.$emit("selectSku", {
            // sku: this.selectedSku,                   // SKU 对象
             skuId: this.selectedSku.id || this.selectedSku.skuId, // SKU ID
             quantity: safeQuantity,                  // 数量
             specs: { ...this.selectedSpecs }         // 已选规格对象
           })
		this.handleClose()
      }
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.spec-modal {
  padding: 20rpx;
}
.spec-group {
  margin-bottom: 20rpx;
}
.spec-title {
  font-weight: bold;
  margin-bottom: 10rpx;
}
.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}
.sku-info {
  margin: 20rpx 0;
  display: flex;
  justify-content: space-between;
}
.quantity-box {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}
</style>
